package com.itheima.ydd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.service.ISysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    /**
     * 查询是否有子菜单,没有则删除
     *
     * @param id
     * @return
     */
    @Override
    public ResultData removeWithOutPid(Integer id) {
        if (super.count(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, id)) > 0) {
            throw new BusinessException("存在作为子级的菜单,不允许删除!");
        }
        super.removeById(id);
        return ResultData.ok("删除成功");
    }

    /**
     * 获取所有菜单信息
     *
     * @return
     */
    @Override
    public ResultData listWithChi() {
        List<SysMenu> list = super.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, 0));
        List<MenuDto> menuDtoList = list.stream().map(item -> {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(item, menuDto);
            childList(menuDto);
            return menuDto;
        }).collect(Collectors.toList());
        return ResultData.ok(menuDtoList);
    }

    /**
     * 递归向下查询子菜单
     *
     * @param
     */
    @Override
    public void childList(MenuDto menuDto) {
        List<SysMenu> list = super.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, menuDto.getId()));
        if (list.isEmpty()) {
            return;
        }
        List<MenuDto> collect = list.stream().map(item -> {
            MenuDto childMenuDto = new MenuDto();
            BeanUtils.copyProperties(item, childMenuDto);
            childList(childMenuDto);
            return childMenuDto;
        }).collect(Collectors.toList());
        menuDto.setChildren(collect);
    }
}
